#include "chat_room.h"
#include "ui_chat_room.h"

//将服务器地址和端口填到此处
QString addr = "df.cylk.codes";
const int port = 3000;
//转换域名为ip地址
QHostInfo info = QHostInfo::fromName(addr);  //优先转换为ipv6地址，注意ipv6端口是否被封
QString ip = info.addresses().first().toString();
const QHostAddress server_addr(ip);



QString yourname; //记录用户名
bool ifname = 0; //判断是否输入用户名
QUdpSocket* socket; //创建一个udp

chat_room::chat_room(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::chat_room)
{
    ui->setupUi(this);
    socket = new QUdpSocket(this);
    socket->connectToHost(server_addr, port); //通过udp连接服务器
    //ui->display->append(server_addr.toString());
    if(socket->state() == QAbstractSocket::ConnectedState){
        ui->display->append("已连接到服务器");}
    else{
        ui->display->append("未连接到服务器");}

    //输入用户名
    dialog();

    QString push_name;
    push_name = "name "+yourname;
    socket->writeDatagram(push_name.toUtf8(), server_addr, port);//向服务器传输用户名

    connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead())); //连接监听函数

    setAttribute(Qt::WA_DeleteOnClose);//保证析构函数起作用
}

chat_room::~chat_room()
{
    QString exit = "exit "+yourname;    //退出时向服务器反馈
    socket->writeDatagram(exit.toUtf8(), server_addr, port);
    ifname = 0;
    delete ui;

}

void chat_room::onReadyRead()
{
    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());         //接受服务器信息
        QHostAddress sender;
        quint16 senderPort;

        socket->readDatagram(datagram.data(), datagram.size(),  //读取信息
                             &sender, &senderPort);

        QString message = QString::fromUtf8(datagram);

        if(message.startsWith("now_member")) {
            QStringList parts = message.split(' '); //分离信息，如果开头为now_member执行用户数更新功能
            ui->num->setText(parts.at(1));
            qDebug() << "nowuser" << parts.at(1);
        } else{
            ui->display->append(message);
            qDebug() << "Received message from server: " << message;       //将信息显示到显示框
        }
    }
}

void chat_room::on_push_clicked()//弹出用户名输入弹窗
{
    if(!ifname) chat_room::dialog();
    else{
    QString message = ui->input->toPlainText();
    ui->input->clear();
    ui->display->append("我:"+message);
    QString post ="";
    post += yourname+": "+message;
    socket->writeDatagram(post.toUtf8(), server_addr, port);
    }
}

void chat_room::dialog(){
    bool ok;
    yourname= QInputDialog::getText(this, tr("请输入你的名字"),tr("请输入你的名字"), QLineEdit::Normal,0, &ok);
    if (!ok) {
        // 用户取消了输入，退出程序

    } else if (yourname.isEmpty()) {
        // 用户输入为空，重新弹窗
        chat_room::dialog();

        // ...
    } else {
        // 用户输入了名字，继续执行程序
        ifname=1;
        return;
    }
}
